package com.hhs.storage.config;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hhs.storage.bean.AttachmentList;
import com.hhs.storage.bean.ProjectMember;
import com.hhs.storage.bean.ProjectPlan;
import com.hhs.storage.service.AttachmentListService;
import com.hhs.storage.service.ProjectMemberService;
import com.hhs.storage.service.ProjectPlanService;
import com.hhs.storage.util.DateEasy;
import com.zaxxer.hikari.HikariDataSource;
import com.zaxxer.hikari.HikariPoolMXBean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.io.File;
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryMXBean;
import java.lang.management.MemoryUsage;
import java.lang.management.ThreadMXBean;
import java.text.SimpleDateFormat;
import java.util.List;

/**
 * @author: HuangHaiShui
 * @description:
 * @date: 2022/3/19 13:58
 * @version: 1.0
 */
@Component
@Slf4j
public class Scheduler {
    @Value("${upload.handlerName}")
    private String baseFileUrl;
    @Resource
    private DataSource dataSource;
    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    @Resource
    private ProjectMemberService projectMemberService;
    @Resource
    private ProjectPlanService projectPlanService;
    @Resource
    private AttachmentListService attachmentListService;
//    @Scheduled(fixedRate = 1000*60*60)
    public void agreeTasks() {
        log.info("============================定时处理项目等待项==============================");
        QueryWrapper<ProjectMember> qw=new QueryWrapper<>();
        qw.eq("agree_status",0);
        qw.or().isNull("agree_status");
        List<ProjectMember> listPm = projectMemberService.list(qw);
        DateEasy now=new DateEasy();
        for (ProjectMember p :
                listPm) {
            String projectId = p.getProjectId();
            ProjectPlan projectPlan = projectPlanService.getById(projectId);
            Integer agreeTime = projectPlan.getAgreeTime();//同意的小时数
            int rat=24;
            if(agreeTime!=null){
                rat=agreeTime;
            }
            if(p.getCreateTime()==null){
                p.setAgreeStatus(1);
                projectMemberService.updateById(p);
            }else {
                long distanceMSeconds = DateEasy.getDistanceMSeconds(new DateEasy(p.getCreateTime()).toYYYYhMMhDDhHHcMMcSS(), now.toYYYYhMMhDDhHHcMMcSS());
                log.info("---------------------------"+distanceMSeconds+"-----------------------------");
                if(distanceMSeconds>rat*1000*60*60){
                    p.setAgreeStatus(1);
                    projectMemberService.updateById(p);
                }
            }
        }
    }
//    @Scheduled(cron = "0 0 3 1 * ?")
    public  void fileReci(){
        String base=baseFileUrl.substring(baseFileUrl.indexOf(":")+1);
        System.out.println("=============文件垃圾清理定时器============");
        File root=new File(base+"attachmentList");
        File[] files = root.listFiles();
        if(files!=null)
        for (File s : files) {
            QueryWrapper<AttachmentList> qw=new QueryWrapper<>();
            qw.like("url",s.getName());
            int count = attachmentListService.count(qw);
            if(count==0){
                s.delete();
            }
        }
    }
    private void getWxToken(){
    }

//    @Scheduled(cron = "0/20 * * * * ?")

    /**
     * 内存检测调试
     * @throws Exception
     */
    public void performanceTest() throws Exception {
        ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
        MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean();
        MemoryUsage heapMemoryUsage = memoryMXBean.getHeapMemoryUsage();
        long used = heapMemoryUsage.getUsed();
        long max = heapMemoryUsage.getMax();
        long committed = heapMemoryUsage.getCommitted();
        double v = used * 1.0;
        MemoryUsage nonHeapMemoryUsage = memoryMXBean.getNonHeapMemoryUsage();
        long nonHeapUsed = nonHeapMemoryUsage.getUsed();
        long nonHeapMax = nonHeapMemoryUsage.getMax();
        long nonHeapCommitted = nonHeapMemoryUsage.getCommitted();
        String dataBasePool = "DataBasePool=[]";
        if (dataSource instanceof HikariDataSource) {
            HikariDataSource ds2 = (HikariDataSource)dataSource;
            HikariPoolMXBean hikariPoolMXBean = ds2.getHikariPoolMXBean();
            dataBasePool = String.format("DataBasePool=[ActiveConnections=%s, IdleConnections=%s, ThreadsAwaitingConnection=%s, TotalConnections=%s, " +
                            "MaximumPoolSize=%s, MinimumIdle=%s, IdleTimeout=%s, ConnectionTimeout=%s]",
                    hikariPoolMXBean.getActiveConnections(),
                    hikariPoolMXBean.getIdleConnections(),
                    hikariPoolMXBean.getThreadsAwaitingConnection(),
                    hikariPoolMXBean.getTotalConnections(),
                    ds2.getMaximumPoolSize(),
                    ds2.getMinimumIdle(),
                    ds2.getIdleTimeout(),
                    ds2.getConnectionTimeout());
        }
        log.info("ThreadCount={}, PeakThreadCount={}, TotalStartedThreadCount={}, DaemonThreadCount={}, " +
                        "HeapMemoryUsage%={}, HeapMemoryMaxUsage%={}, NonHeapMemoryUsage%={}, NonHeapMemoryMaxUsage%={}, " +
                        "{}," +
                        "HeapMemoryUsage=[{}], NonHeapMemoryUsage=[{}], ObjectPendingFinalizationCount={}",
                // Thread
                threadMXBean.getThreadCount(),
                threadMXBean.getPeakThreadCount(),
                threadMXBean.getTotalStartedThreadCount(),
                threadMXBean.getDaemonThreadCount(),
                // Memory
                String.format("%.2f%%", used * 1.0 / committed),
                String.format("%.2f%%", max * 1.0 / committed),
                String.format("%.2f%%", nonHeapUsed * 1.0 / nonHeapCommitted),
                String.format("%.2f%%", nonHeapMax * 1.0 / nonHeapCommitted),
                // DataBasePool
                dataBasePool,
                // Others
                heapMemoryUsage,
                nonHeapMemoryUsage,
                memoryMXBean.getObjectPendingFinalizationCount()
        );
    }
}
